package com.zjj.fanshe.reflect.repo;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.lang.reflect.Field;
import java.util.stream.Stream;

/**
 * @author zhoujunjie
 * @desc TODO
 * @date
 */
/**
 * 反射: “暴力破解”
 * 1.破坏封装性
 * 2.破坏泛型
 *
 * 需求：获取对象的所有属性及其值，以 name-张三 ，num-101 ， age=18存入obj.txt文件中
 * 格式如下：
        ----------Teacher+-----------
        name - 王朝
        workAge - 10
        major - 舞蹈
        ----------Student+-----------
        name - 张三
        num - 101
        age - 18
 */
public class RepoTest {

    public static void main(String[] args) {
        Teacher teacher = new Teacher("王朝" , 10 , "跳舞");
        print(teacher);

        Student student = new Student("张三" , 18 , 101);
        print(student);
    }

    public static void print(Object obj){
        try (
            PrintStream ps = new PrintStream(new FileOutputStream("obj.txt" , true))
        ){
            //改变打印流的输出方向
            System.setOut(ps);

            //1.获取obj对象的类类型
            Class<?> clazz = obj.getClass();
            System.out.println("----------"+clazz.getSimpleName()+"+-----------");

            //2.获取类中所有的属性
            Field[] fields = clazz.getDeclaredFields();
            Stream.of(fields).forEach(field -> {
                //3.取消访问权限检查
                field.setAccessible(true);

                //4.获取属性名及其值，写至文件中
                try {
                    System.out.println(field.getName() +" - "+field.get(obj));
                } catch (IllegalAccessException e) {
                    throw new RuntimeException(e);
                }
            });
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

}
